//
//  ViewController.m
//  15. Particle System
//
//  Created by iD Student on 7/8/13.
//  Copyright (c) 2013 iD Student. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    timer = [NSTimer scheduledTimerWithTimeInterval:.033 target:self selector:@selector(update) userInfo:nil repeats:YES];
    particles = [[NSMutableArray alloc]init];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) update
{
    int i = 0;
    while (i < particles.count) {
        Particle *p = [particles objectAtIndex:i];
        if([p isAlive])
        {
            [p update];
            i++;
        }
        else {
            [p.image removeFromSuperview];
            [particles removeObject:p];
        }
        
    }
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    
    int particlesToSpawn = 30;
    int maxVelocityX = 6;
    int maxVelocityY = 6;
    int maxLifeTime = 30;
    for (int i = 0; i < particlesToSpawn; i++) {
        Particle *particle = [[Particle alloc]init];
        particle.image.center = touchPoint;
        particle.velocityX = arc4random() % (maxVelocityX*2) - maxVelocityX;
        particle.velocityY = arc4random() % (maxVelocityY*2) - maxVelocityY;
        particle.lifetime = arc4random() % maxLifeTime + 30;
        [particles addObject:particle];
        [self.view addSubview:particle.image];
    }
}

@end
